/*
 * @Author: Lucky-Firstsnow firstsnow1119@163.com
 * @Date: 2024-04-28 14:44:18
 * @LastEditors: Lucky-Firstsnow firstsnow1119@163.com
 * @LastEditTime: 2024-07-02 16:08:00
 * @FilePath: \vue3-lucky\src\utils\http.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

/**
 * http 请求基础配置
 */
// const baseURL = 'http://192.168.33.113:8082'
const baseURL = 'http://192.168.1.3:8082'

const httpInterceptor = {
    // 请求拦截前触发
    invoke(options) {
        // 1. 非 http 请求开头需要拼接 baseURL
        if (!options.url?.startsWith('http')) {
            options.url = baseURL + options.url
        }
        // 2, 请求超时 默认 60s
        options.timeout = 10000
        // 3, 添加 header
        options.header = {
            ...options.header,
            'source-client': 'miniapp',
        }
        // 4， token
        // const token = uni.getStorageSync('token')
        var tokenName = uni.getStorageSync('tokenName');    // 从本地缓存读取tokenName值
        var tokenValue = uni.getStorageSync('tokenValue');    // 从本地缓存读取tokenValue值
        if (tokenName != undefined && tokenName != '') {
            options.header[tokenName] = tokenValue;
        }
        // if (token) {
        //     options.header.Authorization = token
        // }        // console.log(options)

    },
}

uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFile', httpInterceptor)

export const API = (options) => {
    return new Promise((resolve, reject) => {
        uni.request({
            ...options,
            // success
            success(res) {
                if (res.statusCode >= 200 && res.statusCode < 300) {
                    resolve(res.data)
                } else if (res.statusCode === 401) {
                    uni.navigateTo({
                        url: '/pages/login/login',
                    })
                    reject(res)
                } else {
                    // 其他错误
                    uni.showToast({
                        icon: 'none',
                        title: (res.data).msg || '请求错误',
                    })
                    reject(res)
                }
            },
            fail(result) {

                uni.navigateTo({
                    url: '/pages/login/login',
                })
                uni.showToast({
                    icon: 'none',
                    title: '网络错误',
                })
                reject(result)
            },
        })
    })
}
